package com.qzdsoft.erpcloud.service.stock.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.qzdsoft.erpcloud.domain.stock.StockOutboundDetail;
import com.qzdsoft.erpcloud.mapper.proj.MaterialQueryMapper;
import com.qzdsoft.erpcloud.mapper.stock.StockOutboundDetailInfoMapper;
import com.qzdsoft.erpcloud.mapper.stock.StockOutboundDetailMapper;
import com.qzdsoft.erpcloud.service.stock.StockOutBoundDetailService;
import com.qzdsoft.erpcloud.vo.proj.MaterialInfo;
import com.qzdsoft.erpcloud.vo.stock.StockOutboundDetailEditInfo;
import com.qzdsoft.erpcloud.vo.stock.StockOutboundDetailEditItemInfo;
import com.qzdsoft.erpcloud.vo.stock.StockOutboundDetailInfo;
import com.qzdsoft.erpcloud.vo.stock.StockOutboundDetailQueryInfo;
import com.qzdsoft.utils.StringUtil;
import com.qzdsoft.vo.Response;
import com.qzdsoft.vo.ResultEnum;

@Service
public class StockOutBoundDetailServiceImpl
        implements StockOutBoundDetailService
{
    private static final Logger logger = org.slf4j.LoggerFactory.getLogger(StockOutBoundDetailServiceImpl.class);
    @Autowired
    StockOutboundDetailInfoMapper stockOutboundDetailInfoMapper;
    @Autowired
    StockOutboundDetailMapper stockOutboundDetailMapper;
    @Autowired 
    MaterialQueryMapper materialMapper;

    @Override
    public List<StockOutboundDetailInfo> selectAll(StockOutboundDetailQueryInfo info)
    {
        return stockOutboundDetailInfoMapper.selectAll(info);
    }

    @Override
    @Transactional
    public Response<String> remove(List<Integer> ids)
    {
        int counts = stockOutboundDetailInfoMapper.deleteByIds(ids);
        if(counts!=ids.size()) {
            throw new RuntimeException("更新数据不对deletecount="+counts);
        }
        return new Response<String>(ResultEnum.SUCCESS);
    }

    @Override
    @Transactional
    public Response<String> edit(StockOutboundDetailEditInfo info)
    {
        logger.debug("编辑销售出库单详情提交数据为{}",info);
        List<StockOutboundDetailEditItemInfo> details = info.getItems();
        if(CollectionUtils.isEmpty(details)) {
            logger.error("编辑销售出库单详情提交数据为空");
            return new Response<>(ResultEnum.ERROR);
        }
//      int taxPrice=0,noTaxPrice=0,tax=0;
        List<StockOutboundDetail> adddetails = new ArrayList<StockOutboundDetail>();//新增的销售出库单详情
        List<StockOutboundDetail> editDetails = new ArrayList<StockOutboundDetail>();//修改的销售出库单详情
        for(StockOutboundDetailEditItemInfo d:details) {
            StockOutboundDetail detail = new StockOutboundDetail();
            if(!StringUtil.isEmpty(d.getId())) {
                detail = stockOutboundDetailMapper.selectByPrimaryKey(d.getId());
                if(detail==null) {
                    logger.error("编辑出库单明细时,根据id,没找到相应的明细数据，可能改明细不存在",d.getId());
                    throw new RuntimeException("编辑出库单明细时,根据id,没找到相应的明细数据，可能改明细不存在");
                }
                editDetails.add(detail);
            }else {
                if(d.getOutboundDate()==null) {
                    detail.setOutboundDate(new Date());
                }
                adddetails.add(detail);
                detail.setQuantityDue(d.getQuantityDue());
            }
            detail.setOutboundId(info.getOutboundId());
            detail.setBillNo(info.getBillNo());
            detail.setMaterialId(d.getMaterialId());
            MaterialInfo material = materialMapper.selectById(d.getMaterialId());
            if(material==null) {
                logger.error("物料id，根据物料id：{},没找到对应的物料信息");
                throw new RuntimeException("物料id错误");
            }
            //物料有关设置
            detail.setMaterialCoding(material.getCode());
            detail.setMaterialSpec(material.getSpec());
            detail.setMaterialTypeId(material.getTypeid());
            detail.setMaterialName(material.getName());
            detail.setMeasurementUId(material.getMearsureUintid());
            detail.setcMaterialCoding(material.getAliasCode());
            detail.setcMaterialName(material.getAliasName());
            detail.setcMaterialSpec(material.getAliasSpec());
            
            detail.setBrandId(material.getBrandid());
            detail.setStoreageId(d.getStoreage());
            detail.setIsGift(d.getIsGift()==0?false:true);
            detail.setActualDelivery(d.getActualdDelivery());
            detail.setPrice(d.getPrice());
            detail.setOutboundDate(d.getOutboundDate());
            
            //CustomerSupplierStatementInfo statement = customerSupplierStatementQueryMapper.selectById(d.getSettlementId());
            //detail.setStatementCurrencyId(statement.getCurrency());
            //detail.setStatementDays(statement.getDates());
            //detail.setStatementExchangeRate(statement.getExchangeRate());
           
            //设置税率
//            TypeInfo taxInfo = supplierCustomerMapper.selectTaxInfo(info.getCompanyid(), info.getSupplierid());
            //detail.setStatementTaxRate(Integer.parseInt(taxInfo.getValue()));
            
//            int price = d.getPrice()*d.getNum();
//            noTaxPrice += price;
//            tax += Integer.parseInt(taxInfo.getValue())*price/100;
        }
//        taxPrice = tax+noTaxPrice;
//        PurchaseOrder order = purchaseOrderMapper.selectByPrimaryKey(info.getBillid());
//        order.setTax(tax);
//        order.setNoTaxPrice(noTaxPrice);
//        order.setTaxPrice(taxPrice);
//        int count = purchaseOrderMapper.updateByPrimaryKey(order);
//        if(count!=1) {
//            logger.error("编辑采购订单明细错误，更新数据不对updatecount={}",count);
//            throw new RuntimeException("编辑采购订单明细错误，更新数据不对updatecount="+count);
//        }
        int count=0;
        if(!CollectionUtils.isEmpty(adddetails)) {
            count = stockOutboundDetailMapper.insertList(adddetails);
            if(count!=adddetails.size()) {
                logger.error("编辑出库单明细错误，更新数据不对updatecount={},提交新增数据条数：{}",count,adddetails.size());
                throw new RuntimeException("编辑出库单明细错误，更新数据不对updatecount="+count);
            }
        }
        
        count = 0;
        for(StockOutboundDetail p:editDetails) {
            count += stockOutboundDetailMapper.updateByPrimaryKey(p);
        }
        if(count!=editDetails.size()) {
            logger.error("编辑出库单单明细错误，更新数据不对updatecount={},提交修改数据条数：{}",count,editDetails.size());
            throw new RuntimeException("编辑出库单单明细错误，更新数据不对updatecount="+count);
        }
        return new Response<String>(ResultEnum.SUCCESS);
    }

}
